import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { message } from 'ant-design-vue'
import type { Menu, MenuQuery, CreateMenu, UpdateMenu } from '@/types/api/system/menu'
import { MenuType } from '@/types/api/system/menu'
import {
  getMenuTree,
  getMenuDetail,
  createMenu,
  updateMenu,
  deleteMenus,
  changeMenuStatus
} from '@/api/system/menu'

/**
 * 菜单管理Store
 */
export const useMenuStore = defineStore('menu', () => {
  // ------------ 国际化和工具引入 ------------
  const { t } = useI18n()
  
  // ------------ 加载状态 ------------
  const loading = ref<boolean>(false)
  const submitLoading = ref<boolean>(false)
  
  // ------------ 数据列表 ------------
  const menuList = ref<Menu[]>([])
  
  // ------------ 展开状态 ------------
  const expandedKeys = ref<string[]>([])
  const isExpandAll = ref<boolean>(false)
  
  // ------------ 查询参数 ------------
  const queryParams = reactive<MenuQuery>({
    keyword: '',
    status: undefined
  })
  
  // ------------ 弹窗状态 ------------
  const modalVisible = ref<boolean>(false)
  const iconModalVisible = ref<boolean>(false)
  
  // ------------ 表单状态 ------------
  const formMode = ref<'add' | 'edit'>('add')
  const currentId = ref<string>('')
  
  // 菜单表单数据
  const form = reactive<CreateMenu>({
    name: '',
    parentId: null,
    type: MenuType.MENU,
    icon: '',
    orderNum: 0,
    path: '',
    component: '',
    query: '',
    isExternal: false,
    isCache: false,
    isVisible: true,
    permission: '',
    status: 1
  })
  
  // ------------ 树形数据 ------------
  const parentTreeData = ref<Menu[]>([])
  
  // ------------ 计算属性 ------------
  const formTitle = computed(() => 
    formMode.value === 'add' ? t('menu.add') : t('menu.edit')
  )
  
  // ------------ 数据操作方法 ------------
  /**
   * 获取菜单列表
   */
  const fetchMenuList = async () => {
    try {
      loading.value = true
      const result = await getMenuTree({
        keyword: queryParams.keyword,
        status: queryParams.status
      })
      if (result.success && result.data) {
        menuList.value = result.data.list.map(transformMenuItem)
        
        // 如果是展开全部模式，更新展开键
        if (isExpandAll.value) {
          expandedKeys.value = getExpandKeys(menuList.value)
        }
        
        // 创建父级菜单树形数据
        parentTreeData.value = [{
          id: '0',
          name: t('menu.rootMenu'),
          parentId: '',
          type: MenuType.DIRECTORY,
          icon: '',
          orderNum: 0,
          path: '',
          component: '',
          query: '',
          isExternal: false,
          isCache: false,
          isVisible: true,
          status: 1,
          permission: '',
          createTime: '',
          updateTime: '',
          children: menuList.value,
          statusLoading: false,
        }]
      } else {
        message.error(result.message || t('common.fetchFailed'))
      }
    } catch (error) {
      message.error(t('common.fetchFailed'))
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取菜单详情
   * @param id 菜单ID
   */
  const fetchMenuDetail = async (id: string) => {
    try {
      const result = await getMenuDetail(id)
      if (result.success && result.data) {
        return result.data
      } else {
        message.error(result.message || t('common.fetchDetailFailed'))
        return null
      }
    } catch (error) {
      message.error(t('common.fetchDetailFailed'))
      return null
    }
  }

  /**
   * 删除菜单
   * @param id 菜单ID
   */
  const removeMenu = async (id: string) => {
    try {
      const result = await deleteMenus([id])
      if (result.success) {
        message.success(t('common.deleteSuccess'))
        await fetchMenuList()
        return true
      } else {
        message.error(result.message || t('common.deleteFailed'))
      }
      return false
    } catch (error) {
      message.error(t('common.deleteFailed'))
      return false
    }
  }

  /**
   * 修改菜单状态
   * @param id 菜单ID
   * @param status 状态值
   */
  const changeMenuStatusAction = async (id: string, status: 0 | 1) => {
    try {
      const result = await changeMenuStatus(id, status)
      if (result.success) {
        message.success(t('common.statusChangeSuccess'))
        return true
      } else {
        message.error(result.message || t('common.statusChangeFailed'))
      }
      return false
    } catch (error) {
      message.error(t('common.statusChangeFailed'))
      return false
    }
  }

  /**
   * 修改菜单可见性
   * @param id 菜单ID
   * @param data 菜单表单数据
   */
  const changeMenuVisible = async (id: string, data: CreateMenu) => {
    try {
      const params = convertToUpdateMenuParams(data, id)
      const res = await updateMenu(id, params)
      if (res.success) {
        message.success(t('menu.changeVisibleSuccess'))
        await fetchMenuList()
        return true
      } else {
        message.error(res.message || t('menu.changeVisibleFailed'))
      }
      return false
    } catch (error) {
      message.error(t('menu.changeVisibleFailed'))
      return false
    }
  }

  /**
   * 提交表单
   */
  const submitForm = async () => {
    try {
      submitLoading.value = true
      
      let res
      if (formMode.value === 'add') {
        // 创建菜单
        res = await createMenu(form)
      } else {
        // 更新菜单
        if (!currentId.value) {
          throw new Error(t('menu.idRequired'))
        }
        
        const menuId = String(currentId.value)
        const params = convertToUpdateMenuParams(form, menuId)
        res = await updateMenu(menuId, params)
      }
      
      if (res.success) {
        message.success(formMode.value === 'add' ? t('common.createSuccess') : t('common.updateSuccess'))
        modalVisible.value = false
        await fetchMenuList()
        return true
      } else {
        message.error(res.message || (formMode.value === 'add' ? t('common.createFailed') : t('common.updateFailed')))
      }
      return false
    } catch (error) {
      message.error(formMode.value === 'add' ? t('common.createFailed') : t('common.updateFailed'))
      return false
    } finally {
      submitLoading.value = false
    }
  }

  /**
   * 重置表单
   */
  const resetForm = () => {
    Object.assign(form, {
      name: '',
      parentId: null,
      type: MenuType.MENU,
      icon: '',
      orderNum: 0,
      path: '',
      component: '',
      query: '',
      isExternal: false,
      isCache: false,
      isVisible: true,
      permission: '',
      status: 1
    })
  }
  
  /**
   * 获取展开的节点key
   */
  const getExpandKeys = (list: Menu[]): string[] => {
    const keys: string[] = []
    const traverse = (items: Menu[]) => {
      items.forEach(item => {
        keys.push(item.id)
        if (item.children && item.children.length > 0) {
          traverse(item.children)
        }
      })
    }
    traverse(list)
    return keys
  }

  /**
   * 转换菜单项数据
   */
  const transformMenuItem = (item: Record<string, any>): Menu => {
    return {
      id: String(item.id),
      name: item.name,
      parentId: item.parentId ? String(item.parentId) : null,
      type: convertMenuType(item.type),
      icon: item.icon || '',
      orderNum: Number(item.orderNum || 0),
      path: item.path || '',
      component: item.component || '',
      query: item.query || '',
      isExternal: convertToBoolean(item.isExternal),
      isCache: convertToBoolean(item.isCache),
      isVisible: convertToBoolean(item.isVisible),
      status: Number(item.status),
      permission: item.permission || '',
      createTime: item.createTime || '',
      updateTime: item.updateTime || '',
      children: item.children ? item.children.map(transformMenuItem) : undefined,
      statusLoading: false,
    }
  }

  /**
   * 转换菜单类型
   */
  const convertMenuType = (type: string | number | undefined): MenuType => {
    if (type === MenuType.DIRECTORY || type === MenuType.MENU || type === MenuType.BUTTON) {
      return type
    }
    return MenuType.MENU
  }

  /**
   * 转换布尔值
   */
  const convertToBoolean = (value: any): boolean => {
    if (typeof value === 'boolean') {
      return value
    }
    if (typeof value === 'number') {
      return value === 1
    }
    if (typeof value === 'string') {
      return value.toLowerCase() === 'true' || value === '1'
    }
    return false
  }

  /**
   * 转换为更新菜单参数
   */
  const convertToUpdateMenuParams = (formData: CreateMenu, id: string): UpdateMenu => {
    return {
      name: formData.name,
      parentId: formData.parentId,
      type: formData.type,
      icon: formData.icon,
      orderNum: formData.orderNum,
      path: formData.path,
      component: formData.component,
      query: formData.query,
      isExternal: formData.isExternal,
      isCache: formData.isCache,
      isVisible: formData.isVisible,
      permission: formData.permission,
      status: formData.status
    }
  }

  /**
   * 设置表单弹窗可见性
   */
  const setFormModalVisible = (visible: boolean) => {
    modalVisible.value = visible
    if (!visible) {
      resetForm()
      currentId.value = ''
      formMode.value = 'add'
    }
  }

  /**
   * 设置图标选择弹窗可见性
   */
  const setIconModalVisible = (visible: boolean) => {
    iconModalVisible.value = visible
  }

  return {
    loading,
    submitLoading,
    menuList,
    expandedKeys,
    isExpandAll,
    queryParams,
    modalVisible,
    iconModalVisible,
    formMode,
    currentId,
    form,
    parentTreeData,
    formTitle,
    fetchMenuList,
    fetchMenuDetail,
    removeMenu,
    changeMenuStatusAction,
    changeMenuVisible,
    submitForm,
    resetForm,
    setFormModalVisible,
    setIconModalVisible
  }
}) 